<template>
  <div>
    <div class="appBox">

      <div class="topReturn flex_sb">
        <div class="flex left">
          <div class="cup flex"
               @click="$router.go(-1)">
            <el-icon size="18">
              <Back />
            </el-icon>
            <div class="ruturn">返回</div>
          </div>
          <div class="title">{{ $route.query.id ? '编辑推荐规则':"创建推荐规则" }}</div>
        </div>
        <div>

        </div>
      </div>

      <div class="flex_c">
        <el-form ref="ruleFormRef"
                 :model="ruleForm"
                 status-icon
                 :rules="rules"
                 label-width="120px"
                 label-position="right"
                 class="demo-ruleForm mt30">
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="规则名称："
                            prop="ruleName">
                <el-input v-model="ruleForm.ruleName"
                          @input="ruleForm.ruleName = $input.inputLimit('D10012',ruleForm.ruleName)"
                          placeholder="请填写职位名称"
                          maxlength="30"
                          clearable />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="弹出规则："
                            prop="rulePopupRule">
                <el-radio-group v-model="ruleForm.rulePopupRule">
                  <el-radio :label="0">每天弹出一次</el-radio>
                  <el-radio :label="1">每个用户仅一次</el-radio>

                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="推荐地区："
                            prop="ruleRecommendPlace">
                <el-cascader v-model="ruleForm.ruleRecommendPlace"
                             class="w100"
                             :props="cityOptions"
                             clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="推荐日期："
                            prop="time">
                <el-date-picker v-model="ruleForm.time"
                                type="datetimerange"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                range-separator="至"
                                value-format="YYYY-MM-DD HH:mm:ss" />

              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="年龄范围："
                            prop="ruleMinAge">
                <div class="flex">
                  <el-input v-model="ruleForm.ruleMinAge"
                            @input="ruleForm.ruleMinAge = $input.inputLimit('D10008',ruleForm.ruleMinAge)"
                            placeholder="最小年龄"
                            maxlength="2"
                            class="w220"
                            clearable />
                  &emsp;-&emsp;
                  <el-form-item label=""
                                label-width="0"
                                prop="ruleMaxAge">
                    <el-input v-model="ruleForm.ruleMaxAge"
                              @input="ruleForm.ruleMaxAge = $input.inputLimit('D10008',ruleForm.ruleMaxAge)"
                              placeholder="最大年龄"
                              maxlength="2"
                              class="w220"
                              clearable />

                  </el-form-item>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="用户范围："
                            prop="ruleUserRange">
                <el-checkbox v-model="checkAll"
                             :indeterminate="isIndeterminate"
                             @change="handleCheckAllChange">全选</el-checkbox>
                &emsp;&emsp;
                <el-checkbox-group v-model="ruleForm.ruleUserRange"
                                   @change="handleCheckedCitiesChange">

                  <el-checkbox :label="1">新实名用户</el-checkbox>
                  <el-checkbox :label="2">未就职用户</el-checkbox>
                  <el-checkbox :label="3">女性</el-checkbox>
                  <el-checkbox :label="4">男性</el-checkbox>

                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="mb20 flex_sb">
        <div></div>
        <div>
          <span class="f14 error">推荐岗位数量最大为10</span>
          <el-button v-preventReClick
                     class="ml20"
                     type="primary"
                     plain
                     @click="dialogVisible = true">添加岗位</el-button>
          <el-button v-preventReClick
                     type="primary"
                     @click="submit">保存</el-button>
        </div>
      </div>

      <el-table border
                :data="tableData"
                style="width: 100%"
                :header-cell-style="{ color: '#000' }">
        <el-table-column prop=""
                         width="100"
                         align="center"
                         label="排序">
          <template #default="scope">
            {{ scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column prop="positionName"
                         label="岗位名称"
                         show-overflow-tooltip
                         align="center">
        </el-table-column>
        <el-table-column prop="companyName"
                         label="所属企业"
                         show-overflow-tooltip
                         align="center">
        </el-table-column>
        <el-table-column prop=""
                         label="操作"
                         align="center"
                         width="120">
          <template #default="scope">
            <div class="btnsDatil flex_c cup primary">
              <!-- 其它操作 -->
              <div @click="handleAction('delete', scope.row,scope.$index)"
                   class="ml14">删除</div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- <div class="pagination">
        <el-pagination background
                       v-model:current-page="params.pageNum"
                       v-model:page-size="params.pageSize"
                       :page-sizes="[10, 20, 30, 50]"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="totalSize"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" />
      </div> -->
    </div>
    <el-dialog v-model="dialogVisible"
               title="添加推荐岗位"
               :width="$px2rem('1100px')"
               :before-close="handleClose">
      <div class="dialogVisibleBox">
        <div class="searchList">
          <el-form :model="params1"
                   ref="FormInstance "
                   class="boxFrom flex_sb">
            <div class="searchBox flex">
              <template v-for="(item, index) in totalInputColumns1"
                        :key="index">
                <el-form-item class="mr10"
                              v-if="item.type == 'input'">
                  <el-input v-model="params1[item.key]"
                            clearable
                            :placeholder="item.label"></el-input>
                </el-form-item>
                <el-form-item class="mr10"
                              v-if="item.type == 'select'">
                  <el-select v-model="params1[item.key]"
                             :placeholder="item.label"
                             clearable
                             v-if="item.key == 'status'">
                    <el-option label="启用"
                               value="1" />
                    <el-option label="禁用"
                               value="0" />
                  </el-select>

                </el-form-item>
                <el-form-item class="mr10"
                              v-if="item.type == 'time'">
                  <el-date-picker v-model="params1[item.key]"
                                  type="date"
                                  value-format="YYYY-MM-DD"
                                  placeholder="请选择时间" />
                </el-form-item>
              </template>
            </div>

            <el-form-item class="btns">
              <el-button v-preventReClick
                         type="primary"
                         plain
                         @click="handleAction('query')">搜索</el-button>
              <el-button v-preventReClick
                         @click="handleAction('reset')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table border
                  :data="tableData1"
                  style="width: 100%"
                  :header-cell-style="{ color: '#000' }">
          <el-table-column prop="positionName"
                           label="岗位名称"
                           show-overflow-tooltip
                           align="left">
          </el-table-column>
          <el-table-column prop="companyName"
                           label="所属企业"
                           show-overflow-tooltip
                           align="left">
          </el-table-column>
          <el-table-column prop=""
                           label="操作"
                           align="center"
                           width="100">
            <template #default="scope">
              <div class="btnsDatil primary cup">
                <!-- 其它操作 -->
                <div @click="handleAction('tj1', scope.row,scope.$index)"
                     v-if="!tableData_ids.includes(scope.row.positionId)">添加</div>
                <div @click="handleAction('tj2', scope.row,scope.$index)"
                     v-if="tableData_ids.includes(scope.row.positionId)"
                     class="">取消添加</div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination background
                         v-model:current-page="params1.pageNum"
                         v-model:page-size="params1.pageSize"
                         :page-sizes="[10, 20, 30, 50]"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="totalSize1"
                         @size-change="handleSizeChange1"
                         @current-change="handleCurrentChange1" />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-preventReClick
                     @click="dialogVisible = false">取消</el-button>
          <el-button v-preventReClick
                     type="primary"
                     @click="handleAction('tj3')">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  ref,
  onMounted,
  reactive,
  toRefs,
  defineComponent,
  getCurrentInstance,
  nextTick,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

export default defineComponent({

  setup () {
    const router = useRouter();
    const route = useRoute();
    const app = getCurrentInstance()?.proxy;
    const initState = () => {
      return {
        checkAll: false,
        isIndeterminate: false,

        cityOptions: {
          checkStrictly: true,
          lazy: true,
          lazyLoad (node, resolve) {
            const { level } = node;
            let nodes = [];
            setTimeout(() => {
              if (level == 0) {
                app.$http.get("/sys/addr/getProvince/list").then((res) => {
                  res.data.forEach((data) => {
                    nodes.push({
                      value: data.id,
                      label: data.name,
                      leaf: true,
                    });
                  });
                  resolve(nodes);
                });
              }
              if (level == 1) {
                app.$http
                  .get("/sys/addr/getProvince/list?pid=" + node.data.value)
                  .then((res) => {
                    res.data.forEach((data) => {
                      nodes.push({
                        value: data.id,
                        label: data.name,
                        leaf: true,
                      });
                    });
                    resolve(nodes);
                  });
              }
              if (level == 2) {
                app.$http
                  .get("/sys/addr/getProvince/list?pid=" + node.data.value)
                  .then((res) => {
                    res.data.forEach((data) => {
                      nodes.push({
                        value: data.id,
                        label: data.name,
                        leaf: true,
                      });
                    });
                    resolve(nodes);
                  });
              }
            }, 100);
          },


        },
        dialogVisible: false,
        ruleForm: {
          ruleName: '',
          rulePopupRule: '',
          ruleRecommendPlace: '',
          ruleStartTime: '',
          ruleEndTime: '',
          ruleMinAge: '',
          ruleMaxAge: '',
          ruleUserRange: []
        },
        rules: {
          ruleName: [
            { required: true, message: "请输入规则名称", trigger: "blur" },
          ],
          rulePopupRule: [
            { required: true, message: "请选择推荐规则", trigger: "blur" },
          ],
          ruleRecommendPlace: [
            { required: true, message: "请输入推荐地区", trigger: "blur" },
          ],
          ruleStartTime: [
            { required: true, message: "请选择开始时间", trigger: "blur" },
          ],
          time: [
            { required: true, message: "请选择推荐日期", trigger: "blur" },
          ],
          ruleEndTime: [
            { required: true, message: "请选择结束时间", trigger: "blur" },
          ],
          ruleMinAge: [
            { required: true, message: "请输入最小年龄", trigger: "blur" },
          ],
          ruleMaxAge: [
            { required: true, message: "请输入最大年龄", trigger: "blur" },
          ],
          ruleUserRange: [
            { required: true, message: "请选择用户范围", trigger: "blur" },
          ],
        },
        params: {
          pageNum: 1,
          pageSize: 10,
          name: "",
          time: '',
        },
        totalSize: 0,
        tableData: [],

        totalSize1: 0,
        tableData1: [

        ],
        params1: {
          pageNum: 1,
          pageSize: 10,
        },
        totalInputColumns1: [
          { key: "cname", label: "搜索企业", type: "input" },
          { key: "pname", label: "搜索岗位名称", type: "input" },
        ],
        tableData_add: [],
        tableData_ids: [],
      };
    };
    const state = reactive(initState());
    onMounted(() => {
      methods.getDataList1()
      if (app.$route.query.id) {
        methods.getDataList();
      }
    });
    const methods = {
      handleCheckAllChange (val) {
        console.log(val);
        state.ruleForm.ruleUserRange = val ? [1, 2, 3, 4] : [];
        state.isIndeterminate = false;
      },
      handleCheckedCitiesChange (value) {
        console.log(value);
        let checkedCount = value.length;
        state.checkAll = checkedCount === 4;
        state.isIndeterminate = checkedCount > 0 && checkedCount < 4;
      },
      submit () {
        app.$refs.ruleFormRef.validate((valid) => {
          if (valid) {
            let url = 'recommendrule/save'
            if (app.$route.query.id) {
              url = 'recommendrule/updateRule'
            }
            if (state.ruleForm.ruleMaxAge < state.ruleForm.ruleMinAge) {
              return ElMessage.error('最大年龄不能小于最小年龄')
            }
            state.ruleForm.ruleStartTime = state.ruleForm.time[0]
            state.ruleForm.ruleEndTime = state.ruleForm.time[1]
            state.ruleForm.recommendPositionRelationList = []
            state.tableData.forEach(item => {
              item.recommendId = app.$route.query.id
              state.ruleForm.recommendPositionRelationList.push(item)
            })

            let data = JSON.parse(JSON.stringify(state.ruleForm))
            app.$post(url, data).then(res => {
              if (res.code == 200) {
                ElMessage.success('保存成功')
                app.$router.go(-1)
              }
            })
          } else {
            return ElMessage.error('请完整选择输入规则')
          }
        })
      },
      handleAction (type, data, index) {
        switch (type) {
          case "query": //查询
            methods.getDataList1();
            break;
          case "reset": // 重置
            state.params1 = initState().params1;
            break;
          case "subAdd": //保存
            methods.subData()
            break;
          case "delete": //
            state.tableData.splice(index, 1)
            console.log(state.tableData);
            state.tableData_ids.splice(state.tableData_ids.indexOf(data.positionId), 1)
            state.tableData_add.forEach((res, index) => {
              if (res.positionId == data.positionId) {
                state.tableData_add.splice(index, 1)
                return
              }
            })
            break;
          case "tj1": //添加
            if ((state.tableData_ids.length - 0) >= 10) {
              return ElMessage.error('推荐岗位数量最大为10')
            }
            state.tableData_ids.push(data.positionId)
            state.tableData_add.push(data)
            break;
          case "tj2": //取消添加
            state.tableData_ids.splice(state.tableData_ids.indexOf(data.positionId), 1)
            state.tableData_add.forEach((res, index) => {
              if (res.positionId == data.positionId) {
                state.tableData_add.splice(index, 1)
                return
              }
            })
            break;
          case "tj3": //确定添加
            state.tableData = state.tableData_add
            state.dialogVisible = false
            break;
        }
      },

      getDataList () {
        app.$get('recommendrule/queryRuleDetails?ruleid=' + app.$route.query.id).then(res => {
          if (res.data) {
            res.data.ruleUserRange = JSON.parse(res.data.ruleUserRange)
            if (res.data.ruleUserRange.length == 4) {
              state.checkAll = true
              state.isIndeterminate = false
            } else {
              state.checkAll = false
              state.isIndeterminate = true
            }
            res.data.ruleRecommendPlace = JSON.parse(res.data.ruleRecommendPlace)

            state.ruleForm = res.data
            state.ruleForm.time = [state.ruleForm.ruleStartTime, state.ruleForm.ruleEndTime]
            state.tableData = res.data.recommendPositionRelationList
            state.tableData_ids = res.data.recommendPositionRelationList.map(a => a.positionId)
            state.tableData_add = JSON.parse(JSON.stringify(state.tableData))
          }
        })
        // app.$get("/sysShare/getById", { id: route.query.id })
        //   .then((res) => {
        //     if (res.code == 200) {
        //     }
        //   });
      },
      getDataList1 () {
        app.$get('/recommendrule/queryPosition', state.params1).then(res => {
          if (res.data.data) {
            state.tableData1 = res.data.data
            state.totalSize1 = res.data.total
          }
        })
      },
      //分页变化
      handleSizeChange () {
        state.params.pageNum = 1;
        methods.getDataList();
      },
      //表格翻页
      handleCurrentChange () {
        methods.getDataList();
      },
      //分页变化
      handleSizeChange1 () {
        state.params1.pageNum = 1;
        methods.getDataList1();
      },
      //表格翻页
      handleCurrentChange1 () {
        methods.getDataList1();
      },
    }
    return {
      ...toRefs(state),
      ...methods,
    };
  }
});
</script>


<style lang="scss" scoped>
::v-deep(.el-dialog__body) {
  height: 540px;
}
.dialogVisibleBox {
  height: 100%;
  padding: 20px 20px 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
::v-deep(.el-dialog) {
  min-height: 540px;
}
.w220 {
  width: 220px;
}
.active {
  border: 2px solid #409eff !important;
}
.imgBorderBox {
  padding: 5px;
  border-radius: 5px;
  border: 2px solid #ccc;
  margin: 0 10px 10px 0;
}
.topReturn {
  .ruturn {
    color: rgba(121, 121, 121, 1);
    font-size: 16px;
    position: relative;
    margin-left: 10px;
    margin-top: -2px;
  }
  .ruturn::before {
    content: '';
    position: absolute;
    left: 50px;
    top: 4px;
    width: 1px;
    height: 16px;
    background: rgba(121, 121, 121, 0.8);
  }
  .left {
    align-items: center;
  }
  .title {
    color: rgb(83, 83, 83);
    font-size: 16px;
    margin-left: 40px;
    font-weight: bold;
  }
}
.top {
  padding: 30px 40px;
  border-radius: 5px;
}
.imgBox {
  display: flex;
  flex-wrap: wrap;
}
</style>